package com.music.genres.dao.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.music.domain.Music;
import com.music.domain.PageInfo;
import com.music.genres.dao.FindMusicByParamDao;

@Repository
public class FindMusicByParamDaoImpl implements FindMusicByParamDao {
	@Autowired
	SessionFactory sessionFactory;
	@Override
	public List<Music> findMusicByCate(String cate, PageInfo pageInfo) {
		String sql="SELECT COUNT(*) FROM T_MUSIC";
		String hql="from Music";
		if("0".equals(cate)){
			sql+=" WHERE CATEID!=:CATEID";
			hql+=" WHERE cateId!=:CATEID";
		}else{
			sql+=" WHERE CATEID=:CATEID";
			hql+=" WHERE cateId=:CATEID";
		}
		SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(sql);
		Query hqlQuery = sessionFactory.getCurrentSession().createQuery(hql);
		sqlQuery.setParameter("CATEID", cate);
		hqlQuery.setParameter("CATEID", cate);
		BigDecimal number = (BigDecimal) sqlQuery.uniqueResult();
		pageInfo.setNumber(String.valueOf(number));
		pageInfo.setTotal(String.valueOf((int)Math.ceil(Double.parseDouble(pageInfo.getNumber())/Double.parseDouble(pageInfo.getCount()))));
		hqlQuery.setFirstResult((Integer.parseInt(pageInfo.getCurr_total())-1)*(Integer.parseInt(pageInfo.getCount())));
		hqlQuery.setMaxResults(Integer.parseInt(pageInfo.getCount()));
		List<Music> data = hqlQuery.list();
		return data;
	}
}
